<!--
 * @Descripttion: 
 * @Author: Kevin
 * @Date: 2022-06-13 15:07:16
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-08-14
-->
<template>
  <div>
    <LayoutPanel class="private-common-wrapper">
      <div slot="title" class="title">
        <span>{{ $t('localAccount.title') }}</span>
        <rj-space :size="16" class="title-txt">
          <div class="status-item">
            <div class="circle total"></div>
            <span>
              {{ $t('localAccount.totalAccounts') }}{{ statusCount.total }}
            </span>
          </div>
          <div class="status-item">
            <div class="circle used"></div>
            <span>
              {{ $t('localAccount.inUseAccounts') }}{{ statusCount.used }}
            </span>
          </div>
          <div class="status-item">
            <div class="circle expired"></div>
            <span>
              {{ $t('localAccount.expiredAccounts') }}{{ statusCount.expired }}
            </span>
          </div>
        </rj-space>
      </div>
      <!-- 
        :scroll="{ y: 500, x: 1000 }" -->
      <rj-table
        :columns="localAccountColumns"
        :dataSource="data"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          selectedRows: selectedRows,
          onChange: onSelectChange,
        }"
        :pagination="pagination"
        :loading="loading"
        rowKey="uuid"
        filtercolumns
        @refeshTable="getAccountList"
        @change="handleTableChange"
      >
        <div slot="customBlock" class="log-opt-wrapper">
          <a-space :size="16">
            <a-button class="icon-btn" type="primary" @click="onAdd">
              <icon-font type="ic-plus" />
              {{ $t('userManage.addAccount') }}
            </a-button>
            <a-button @click="onBatchAdd"> {{ $t('common.import') }} </a-button>
            <a-dropdown>
              <a-menu slot="overlay">
                <a-menu-item key="1" @click="onDelete(null)">
                  {{ $t('common.delete') }}
                </a-menu-item>
                <a-menu-item key="2" @click="onReset(null)">
                  {{ $t('common.reset') }}
                </a-menu-item>
              </a-menu>
              <a-button class="icon-btn">
                {{ $t('common.more') }} <icon-font type="ic-down" />
              </a-button>
            </a-dropdown>
          </a-space>
          <!-- 过滤搜索 -->
          <a-input-search
            class="w-200"
            :placeholder="$t('userManage.accountPlaceholder')"
            v-model="queryParamObj.name"
            @change="onChangeSearch"
          />
        </div>

        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <rj-space :size="16">
            <icon-font type="ic-edit" @click="onEdit(record)" />
            <icon-font type="ic-redo" @click="onReset(record)" />
            <icon-font type="ic-forbid" @click="onForbid(record)" />
            <icon-font type="ic-delete" @click="onDelete(record)" />
          </rj-space>
        </template>
      </rj-table>
      <AddModal
        @addAuthPolicy="onAddAuthPolicy"
        @refreshList="refreshView"
        ref="addModalRef"
      />
      <AddPolicyModal
        ref="addPolicyModalRef"
        @refreshList="addPolicyCallback"
      />
      <BatchAddModal @refreshList="refreshView" ref="batchAddModalRef" />
    </LayoutPanel>
  </div>
</template>

<script>
import { RjTable } from '@components';
import AddModal from './AddModal.vue';
import AddPolicyModal from '@project/authSys/views/authPolicy/AddModal.vue';
import BatchAddModal from './BatchAddModal.vue';
import { requestHttp, maccApi } from '@utils/index';
import moment from 'moment-timezone';
import { mapState } from 'vuex';
import bindIcon from '@/assets/images/configuration/bind.png';
import { getByteLength, ValiDateTools } from '@/utils';
import { formatPeriod, formatDevice, formatUsage, formatLimit } from './utils';
import LayoutPanel from '@views/common/deviceDetail/components/components/layoutPanel.vue';
import { localAccountColumns } from './columns.js';
import lodash from 'lodash';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
export default {
  name: 'localAccount',
  mixins: [authSysMixin],
  components: {
    AddModal,
    BatchAddModal,
    'rj-table': RjTable,
    LayoutPanel,
    AddPolicyModal,
  },
  data() {
    return {
      isPasswordVisible: false,
      localAccountColumns,
      pagination: {
        pageSizeOptions: ['10', '20', '50', '100'],
        total: 0,
        current: 1,
        pageSize: 10,
      },
      filters: {},
      data: [],
      selectedRowKeys: [],
      selectedRows: [],
      addModalShow: false,
      loading: false,
      queryParamObj: {
        name: '',
        status: '',
      },
      statusCount: {},
      bindIcon,
      batchModalShow: false,
      macModalShow: false,
      oneClickModalShow: false,
      uuid: '',
    };
  },
  mounted() {
    this.getAuthPolicyList();
    this.refreshView();
  },
  computed: {},
  methods: {
    addPolicyCallback(profileId) {
      this.getAuthPolicyList();
      this.$refs.addModalRef.setAuthPolicyId(profileId);
    },
    onAddAuthPolicy() {
      this.$refs.addPolicyModalRef.openModal();
    },
    onTiggerPassword() {
      this.isPasswordVisible = !this.isPasswordVisible;
    },
    onChangeSearch() {
      this.pagination.current = 1;
      this.getListDebounce();
    },
    getListDebounce: lodash.debounce(function () {
      this.getAccountList();
    }, 500),
    refreshView() {
      this.getAccountList();
      this.getStatus();
    },
    filterSearch() {
      this.debounceGetAccountList();
    },
    debounceGetAccountList: lodash.debounce(function () {
      this.pagination.current = 1;
      this.getAccountList();
    }, 500),
    async updateRecord(record, key) {
      const email = (val) => {
        let flag = true;
        if (val && !ValiDateTools.emailRegex.test(val)) {
          this.$message.warning(this.$t('userManage.enterCorrectEmail'));
          flag = false;
        }
        return flag;
      };
      const phone = (val) => {
        let flag = true;
        if (val) {
          if (getByteLength(val) > 25) {
            this.$message.warning(this.$t('userManage.phoneLengthTip'));
            flag = false;
          } else if (!ValiDateTools.numericRegex.test(val)) {
            this.$message.warning(this.$t('userManage.phoneNumberTip'));
            flag = false;
          }
        }
        return flag;
      };

      const firstName = (val) => {
        let flag = true;
        if (val) {
          if (getByteLength(val) > 60) {
            this.$message.warning(this.$t('userManage.nameLengthTip'));
            flag = false;
          } else if (!ValiDateTools.alphaNumericUnderscoreRegex.test(val)) {
            this.$message.warning(
              this.$t('userManage.enterNumbersLettersUnderscores')
            );
            flag = false;
          }
        }
        return flag;
      };

      const lastName = (val) => {
        let flag = true;
        if (val) {
          if (getByteLength(val) > 60) {
            this.$message.warning(this.$t('userManage.nameLengthTip'));
            flag = false;
          } else if (!ValiDateTools.alphaNumericUnderscoreRegex.test(val)) {
            this.$message.warning(
              this.$t('userManage.enterNumbersLettersUnderscores')
            );
            flag = false;
          }
        }
        return flag;
      };

      const alias = (val) => {
        let flag = true;
        if (val) {
          if (getByteLength(val) > 64) {
            this.$message.warning(this.$t('userManage.commentLengthTip'));
            flag = false;
          } else if (
            !ValiDateTools.alphaNumericUnderscoreBlankRegex.test(val)
          ) {
            this.$message.warning(
              this.$t('userManage.enterNumbersLettersUnderscores')
            );
            flag = false;
          }
        }
        return flag;
      };

      const rules = {
        firstName,
        lastName,
        phone,
        email,
        alias,
      };
      let flag = rules[key](record[`new${key}`]);
      if (flag) {
        let params = { ...record, [key]: record[`new${key}`], refName: '' };
        params.groupId = this.groupId;
        params.comment = params.alias;
        let querys = {
          tenantId: this.tenantInfo.tenantId,
          group_id: this.groupInfo.groupId,
        };
        let replaces = {
          groupId: this.groupId,
        };
        let res = await requestHttp({
          api: `${maccApi.USER_MANAGE_ACCOUNT_UPDATE}`,
          method: 'POST',
          querys,
          params,
          replaces,
        });
        if (!res.code) {
          if (!res?.voucherData?.code) {
            this.$message.success(this.$t('userManage.success'));
            this.getAccountList();
          } else {
            this.$message.warning(res.voucherData.msg);
          }
        } else {
          this.$message.warning(res.msg);
        }
      }
      return flag;
    },
    handleTableChange(pagination, filters) {
      this.pagination = pagination;

      // this.filters = filters;
      // this.localAccountColumns.find(
      //   (item) => item.key == 'statusDesc'
      // ).filteredValue = this.filters.statusDesc || null;
      // this
      if (filters.statusDesc && filters.statusDesc.length > 0) {
        this.queryParamObj.status = filters.statusDesc[0];
      } else {
        delete this.queryParamObj.status;
      }

      this.getAccountList();
    },
    openMacModal(row) {
      this.uuid = row.uuid;
      this.macModalShow = true;
    },
    async getStatus() {
      const res = await this.requestHttpAuth({
        api: `${maccApi.MACC_ACCOUNT_STATUS_GET_API}`,
        method: 'GET',
        replaces: {
          groupId: this.groupId,
          tenantName: encodeURI(this.tenantInfo.tenantName),
        },
      });
      if (!res.code) {
        this.statusCount = res.data;
      }
    },
    // 处理请求回来的数据
    dealData(list, flag = false) {
      const statusMap = {
        1: this.$t('userManage.unActivated'),
        2: this.$t('userManage.activated'),
        3: this.$t('userManage.expired'),
      };
      let timeFormatStr = 'YYYY-MM-DD HH:mm:ss';
      return list.map((item) => {
        item.maxUplink = item.maxUplink || 0;
        item.maxDownlink = item.maxDownlink || 0;
        item.profileName = item.profileName || '-';
        if (!item.maxUplink && !item.maxDownlink) {
          item.limit = this.$t('userManage.unlimited');
        } else {
          item.limit = `${formatLimit(item.maxUplink)}/${formatLimit(
            item.maxDownlink
          )}`;
        }
        if (item.bindMac == 1) {
          if (item.status == '2' || item.status == '3') {
            item.bindMacStatus = '1';
          } else {
            item.bindMacStatus = '2';
          }
        } else {
          item.bindMacStatus = '3';
        }
        if (item.bindMacStatus == '1' || item.bindMacStatus == '2') {
          item.bindMacStatusDesc = 'Yes';
        } else {
          item.bindMacStatusDesc = 'No';
        }
        item.alias = item?.comment || '';
        item.firstName = item?.firstName || '';
        item.lastName = item?.lastName || '';
        item.phone = item?.phone || '';
        item.usedQuota = item.usedQuota || 0;
        item.dataUsageAndLimit = `${formatUsage(
          item.usedQuota,
          'used'
        )}/${formatUsage(item.quotalimit, 'limit')}`;

        item.statusDesc = statusMap[item.status];

        item.createTime = moment(Number(item.createTime)).format(timeFormatStr);
        item.expiryTime = item.expiryTime
          ? moment(Number(item.expiryTime)).format(timeFormatStr)
          : '-';
        item.loginTime = item.loginTimeMill
          ? moment(item.loginTimeMill).format(timeFormatStr)
          : '-';
        item.period = formatPeriod(item.timePeriod);
        item.maxClients = item.maxClients || 0;
        item.maxClientsWithUnit = formatDevice(item.maxClients);
        item.devices = `${item.currentClients}/${item.maxClientsWithUnit}`;
        item.disableDesc = !item.disableStatus
          ? this.$t('common.no')
          : this.$t('common.yes');
        return item;
      });
    },
    // 查询数据
    async getAccountList() {
      this.loading = true;

      const queryObj = {
        tenantId: this.tenantInfo.tenantId,
        start: (this.pagination.current - 1) * this.pagination.pageSize,
        pageSize: this.pagination.pageSize,
        name: this.queryParamObj.name,
      };
      if (this.queryParamObj.status) {
        queryObj.status = this.queryParamObj.status;
      }

      const res = await this.requestHttpAuth({
        api: maccApi.MACC_ACCOUNT_GET_API,
        replaces: {
          tenantName: this.tenantInfo.tenantName,
          groupId: this.groupId,
        },
        querys: queryObj,
        method: 'GET',
      });

      this.selectedRowKeys = [];
      this.loading = false;
      if (!res.code) {
        this.pagination.total = res?.data?.count || 0;
        let list = res?.data?.list || [];
        this.data = this.dealData(list);
        return list;
      }
    },
    onEdit(row) {
      this.$refs.addModalRef.openModal(row);
    },
    onAdd() {
      this.$refs.addModalRef.openModal();
    },
    onBatchAdd() {
      this.$refs.batchAddModalRef.openModal();
    },
    // 表格复选框勾选事件
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    // 删除账号
    onDelete(row) {
      if (!row) {
        if (!this.selectedRowKeys.length) {
          this.$message.warning(this.$t('userManage.selectOneAccount'));
          return;
        }
      }
      this.$confirm({
        title: this.$t('userManage.message'),
        content: this.$t('userManage.deleteRecord'),
        onOk: async () => {
          let querys = {
            tenantId: this.tenantInfo.tenantId,
          };
          let params;
          if (row) {
            params = [row.uuid];
          } else {
            params = this.selectedRows.map((item) => item.uuid);
          }
          const res = await this.requestHttpAuth({
            api: maccApi.MACC_ACCOUNT_DEL_API,
            method: 'POST',
            params,
            querys,
          });
          if (!res.code) {
            this.$message.success(this.$t('userManage.success'));
            this.selectedRowKeys = [];
            this.selectedRows = [];
            this.getAccountList();
            this.getStatus();
          } else {
            this.$message.warning(res.msg);
          }
        },
      });
    },
    // 重置账号
    onReset(row = null) {
      let confirmTxt = '';
      if (!row) {
        if (!this.selectedRowKeys.length) {
          this.$message.warning(this.$t('userManage.selectOneAccount'));
          return;
        }
        confirmTxt = this.$t('userManage.resetAccount');
      } else {
        confirmTxt = this.$t('localAccount.resetConfirm');
      }

      this.$confirm({
        content: confirmTxt,
        title: this.$t('userManage.message'),
        onOk: async () => {
          let params = row ? [row.uuid] : this.selectedRowKeys;
          let querys = {
            tenantId: this.tenantInfo.tenantId,
          };
          const res = await this.requestHttpAuth({
            api: maccApi.MACC_ACCOUNT_RESET_POST_API,
            method: 'POST',
            params,
            querys,
          });
          if (!res.data.code) {
            this.$message.success(this.$t('userManage.success'));
            this.selectedRowKeys = [];
            this.selectedRows = [];
            this.getAccountList();
          } else {
            this.$message.warning(res.data.msg);
          }
        },
      });
    },
    onForbid(row) {
      this.$confirm({
        content: row.disableStatus
          ? this.$t('userManage.enabledAccount')
          : this.$t('userManage.disabledAccount'),
        title: this.$t('userManage.message'),
        onOk: async () => {
          const res = await this.requestHttpAuth({
            api: maccApi.MACC_ACCOUNT_DISABLE_POST_API,
            method: 'POST',
            params: {
              ids: [row.uuid],
            },
            querys: {
              tenantId: this.tenantInfo.tenantId,
            },
          });
          if (!res.code) {
            if (!res?.voucherData?.code) {
              this.$message.success(this.$t('userManage.success'));
              this.selectedRowKeys = [];
              this.selectedRows = [];
              this.getAccountList();
            } else {
              this.$message.warning(res.voucherData.msg);
            }
          } else {
            this.$message.warning(res.msg);
          }
        },
      });
    },

    async getAuthPolicyList() {
      const res = await this.requestHttpAuth({
        api: maccApi.MACC_PROFILE_GET_API,
        method: 'GET',
        replaces: {
          tenantName: this.tenantInfo.tenantName,
          groupId: this.groupId,
        },
        querys: {
          tenantId: this.tenantInfo.tenantId,
          start: 0,
          pageSize: 100,
        },
      });
      if (res.data.code === 0) {
        this.$store.commit(
          'AuthCommon/SET_AUTH_POLICY_LIST',
          res?.data?.list || []
        );
      } else {
        this.$message.warning(res.data.msg);
      }
    },
  },
};
</script>

<style scoped lang="less">
.title-item {
  display: flex;
  gap: 4px;
  > span {
    cursor: pointer;
    display: flex;
    align-items: center;
  }
}
.private-common-wrapper {
  padding: 16px;
  .title {
    display: flex;
    justify-content: space-between;
  }
}
.status-item {
  display: flex;
  gap: 4px;
  font-weight: 400;
  align-items: center;
  .circle {
    width: 10px;
    height: 10px;
    border-radius: 50%;
  }
  .total {
    background: #47aefd;
  }

  .used {
    background: #00c55b;
  }

  .expired {
    background: #ff2d00;
  }
}
.log-opt-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
}
.icon-btn {
  i {
    font-size: 15px;
    padding-top: 3px;
  }
}
.flex {
  display: flex !important;
  flex-direction: row !important;
  align-items: center;
}
.w-200 {
  width: 200px;
}
</style>
